//
//  MYGIndInfoViewController.swift
//  MYDoctor
//
//  Created by 王振明 on 2024/4/4.
//

import UIKit
import MJRefresh

class MYGIndInfoViewController: MYGBaseController {
    var keyWords:String = ""
    var page:Int = 1
    var sortKey = -1

    var dataArr:[MYGIndInfoModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        MYGLoading.show()
        getDatasource()
        NotificationCenter.default.addObserver(self, selector: #selector(refresh), name: Notification.Name("MYGIndInfoViewController_refresh"), object: nil)
    }
    
    @objc func refresh() {
        self.page = 1
        getDatasource()
    }
    private func getDatasource(){
        MYGNetwork<MYGHomePageAPI, MYGPageModel<MYGIndInfoModel>>.request(target: .getIndInfoList(param: [
            "key":keyWords,
            "pageSize":"20",
            "page":String(format: "%d", page),
            "sort":"\(self.sortKey + 1)"])) {[weak self] item in
                if self?.page == 1{
                    self?.dataArr.removeAll()
                }
                self?.dataArr.append(contentsOf: item.list)
                self?.tableView.reloadData()
                MYGLoading.hide()
                self?.tableView.mj_header?.endRefreshing()
                if item.page.total <= self?.dataArr.count ?? 0 {
                    self?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                } else {
                    self?.tableView.mj_footer?.endRefreshing()
                }
            } failed: {[weak self] _, error in
                self?.tableView.mj_header?.endRefreshing()
                self?.tableView.mj_footer?.endRefreshing()
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }
    }
    @objc func tapSort() {
        YBPopupMenu.show(at: CGPoint(x: screenWidth - 25, y: navHeight + statusBarHeight + 58), titles: ["浏览量","播放量","时间"], icons: [], menuWidth: 70) { menu in
            menu?.delegate = self
            menu?.dismissOnSelected = true
            menu?.font = UIFont.regular(12)
            menu?.itemHeight = 30
            menu?.selectecIndex = self.sortKey
            menu?.selectedTextColor = UIColor.init(hexString: "#6389F1")
            menu?.separatorColor = .clear
            menu?.textColor = UIColor.init(hexString: "#C0BEBE")
        }
    }
    private func initUI(){
        self.title = "行业资讯"
        view.backgroundColor = .white
        view.addSubview(sortBtn)
        sortBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize.init(width: 47, height: 35))
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(23)
        }
        view.addSubview(serachBView)
        serachBView.snp.makeConstraints { make in
            make.right.equalTo(sortBtn.snp.left)
            make.top.equalToSuperview().offset(23)
            make.left.equalToSuperview().offset(16)
            make.height.equalTo(35)
        }
        
        serachBView.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(11)
            make.right.equalToSuperview().offset(-11)
            make.top.bottom.equalToSuperview()
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(serachBView.snp.bottom).offset(15)
            make.left.right.bottom.equalToSuperview()
        }
    }
    var serachBView: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "#F5F5F5")
        control.addCorner(radius: 17.5)
        return control
    }()
    
    var dataSource = [String]()
    lazy var searchTextField: UITextField = {
        let control = UITextField()
        control.textAlignment = .center
        control.placeholder = "搜索"
        control.delegate = self
        control.clearButtonMode = .whileEditing
        control.returnKeyType = .search
        return control
    }()
    
    lazy var sortBtn: UIButton = {
        let control = UIButton()
        control.setImage(UIImage.init(named: "MYG_topic_sort"), for: .normal)
        control.addTarget(self, action: #selector(tapSort), for: .touchUpInside)
        return control
    }()
    
    lazy var tableView: UITableView = {
        let control = UITableView()
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
        control.register(cellWithClass: MYGIndInfoTableViewCell.self)
        control.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1
            self?.getDatasource()
        })
        control.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.getDatasource()
        })
        return control
    }()
}
extension MYGIndInfoViewController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGIndInfoTableViewCell.self, for: indexPath)
        let model = dataArr[indexPath.row]
        cell.modelIn = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = dataArr[indexPath.row]
        let vc = MYGIndInfoDetailViewController()
        vc.id = model.id
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension MYGIndInfoViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        keyWords = textField.text ?? ""
        textField.resignFirstResponder()
        self.tableView.mj_header?.beginRefreshing()
        return true
    }
}

extension MYGIndInfoViewController:YBPopupMenuDelegate {
    func ybPopupMenu(_ ybPopupMenu: YBPopupMenu!, didSelectedAt index: Int) {
        if index == self.sortKey {
            self.sortKey = -1//再次选中就清空
        }else {
            self.sortKey = index
        }
     
        self.tableView.mj_header?.beginRefreshing()
    }
}
